<?php

// 检查是否有文件
if(!isset($_FILES['file'])) {
    $data = [
        'success' => false,
        'message' => '请上传文件',
    ];
    echo json_encode($data);
    exit;
}

$configs_image = C::t('#erling_gridad_image#configs_image');

$configs = $configs_image->fetch_by_keys([
    'bgimage_on',
    'bgimage_max_size',//kb
    'bgimage_type',
]);

$file = $_FILES['file'];
$max_size = $configs['bgimage_max_size']['value'] * 1024;

// 检查文件大小
if($file['size'] > $max_size) {
    $data = [
        'success' => false,
        'message' => '文件大小超出限制',
    ];
    echo json_encode($data);
    exit;
}

// 检查文件类型 $configs['bgimage_type']['value']是 逗号分隔的字符串
$bgimage_type = $configs['bgimage_type']['value'];
$allowed_extensions = explode(',', $bgimage_type);
$mime_types = [
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png' => 'image/png',
    'gif' => 'image/gif'
];

$allowed_mime_types = [];
foreach ($allowed_extensions as $ext) {
    if (isset($mime_types[$ext])) {
        $allowed_mime_types[] = $mime_types[$ext];
    }
}
$file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

if (!in_array($file['type'], $allowed_mime_types) || !in_array($file_ext, $allowed_extensions)) {
    $data = [
        'success' => false,
        'message' => $file['type'].'文件类型只能是' . $bgimage_type,
    ];
    echo json_encode($data);
    exit;
}

// 上传文件
$upload_dir = dirname(__FILE__) . '/../20cms/upload/';
if(!is_dir($upload_dir)) {
    if(!mkdir($upload_dir, 0755, true)) {
        echo json_encode(['success' => false, 'message' => '无法创建上传目录']);
        exit;
    }
}
$new_name = time() . rand(1000, 9999) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
$upload_file = $upload_dir . $new_name;
if(!move_uploaded_file($file['tmp_name'], $upload_file)) {
    $data = [
        'success' => false,
        'message' => '文件上传失败',
    ];
    echo json_encode($data);
    exit;
}

// 返回上传成功的结果
$data = [
    'success' => true,
    'message' => '文件上传成功',
    'data' => [
        'file_url' => 'source/plugin/erling_gridad_image/20cms/upload/' . $new_name,
    ],
];
echo json_encode($data);
exit;
